import fs from 'fs';
import multer from 'multer';
import path from 'path';
import {
  uploadFolder,
  Folder,
} from '../config/folder';

class FILE {
  /**
   * GetOriginalName
   * @author imsunhao
   * @createTime 2017-12-1 12:40:43
   * @description 获取文件名称与文件类型
   * @param FILE
   * @returns {{originalname: string, type: FILE}}
   */
  static GetOriginalName (FILE) {
    let originalnameStep = FILE.originalname.split('.');
    let type = '.' + originalnameStep.pop();
    let originalname = '';
    originalnameStep.forEach(item => {
      originalname += item;
    });
    originalname = originalname || FILE.originalname;
    type = originalname ? type : '';
    return {
      originalname,
      type,
    };
  }

  /**
   * GetFileName
   * @author imsunhao
   * @createTime 2017-12-1 15:33:12
   * @description 公用文件命名函数
   * @param req
   * @param file
   * @param cb
   * @constructor
   */
  static GetFileName (req, file, cb) {
    let {
      originalname,
      type,
    } = FILE.GetOriginalName(file);
    cb(null, originalname + '-' + Date.now() + type);
  }

  /**
   * remove
   * @author imsunhao
   * @createTime 2017-12-1 15:33:12
   * @description 安全删除文件
   * @param p
   */
  static remove (p) {
    p = path.join(uploadFolder + p);
    console.log((new Date()).toLocaleString() + '  删除文件:  ' + p);
    try {
      fs.unlinkSync(p);
    } catch (err) {
      console.error((new Date()).toLocaleString() + '  删除文件失败！');
    }
  }
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (Folder[file.fieldname]) {
      cb(null, Folder[file.fieldname]);
    } else {
      cb(null, false);
      console.error(req.ip + '  未知文件上传！  ' + (new Date()).toLocaleString());
    }
  },
  filename: FILE.GetFileName,
});
const UpLoad = multer({ storage: storage });

export {
  FILE,
  UpLoad,
};
